import { login, getUserInfo, getUserDetailById } from '@/api'
import { getToken, setToken, removeToken } from '@/utils/auth'
export default {
  namespaced: true,
  state: {
    token: getToken() || '',
    userInfo: {}
  },
  mutations: {
    // 修改token
    SET_TOKEN(state, token) {
      state.token = token
      setToken(token)
    },
    // 删除token
    REMOVE_TOKEN(state) {
      // 清除vuex里的token
      state.token = ''
      // 清除cookie里的token
      removeToken()
    },
    SET_USERINFO(state, userInfo) {
      state.userInfo = userInfo
    }
  },
  actions: {
    async fetchLogin(context, loginForm) {
      const res = await login(loginForm)
      // console.log(res)
      context.commit('SET_TOKEN', res.data)
    },
    async fetchUserInfo(context) {
      const res = await getUserInfo()
      const res2 = await getUserDetailById(res.data.userId)
      context.commit('SET_USERINFO', { ...res.data, ...res2.data })
    }
  }
}
